<?php

namespace app\api\controller;

use think\Controller;
use GatewayClient\Gateway;

/**
 * @title 聊天接口
 */
class Chat extends Controller
{
    /**
     * @title 发送聊天信息
     * @author Leruge
     * @method post
     * @url /api/chat
     *
     * @param name:type type:int require:1 desc:消息类型
     * @param name:client_id type:string require:0 desc:绑定用户的ID
     * @param name:room_num type:string require:0 desc:房间号
     * @param name:content type:string require:0 desc:消息内容
     */
    public function chat()
    {
        Gateway::$registerAddress = '127.0.0.1:1238';
        if (input('type') == 1) {
            $data = [
                'type' => 1,
                'client_id' => input('client_id')
            ];
            $this->bindUser($data);
            $this->result('', 1, '绑定成功', 'json');
        } elseif (input('type') == 2) {
            $data = [
                'type' => 2,
                'room_num' => input('room_num'),
                'content' => input('content')
            ];
            $this->sendMessage($data);
            $this->result('', 1, '发送消息成功', 'json');
        } elseif (input('type') == 3) {
            $data = [
                'type' => 3,
                'room_num' => input('room_num'),
                'content' => input('content')
            ];
            $url = config('extra.app_url') . '/biaoqing/bq' . input('content') . '.png';
            $data['content'] = '<img src="'. $url .'" class="look" />';
            $this->sendMessage($data);
            $this->result('', 1, '发送消息成功', 'json');
        } elseif (input('type') == 4) {
            $data = [
                'type' => 4,
                'room_num' => input('room_num'),
                'content' => request()->file('content')
            ];
            $path = env('root_path') . 'public/uploads/images/';
            $info = controller('tool/tool')->fileCompress($data['content'], 'chat');
            $img = config('extra.app_url') . $info;
            $data['content'] = '<img src="' . $img . '" class="image" />';
            $this->sendMessage($data);
            $this->result('', 1, '发送消息成功', 'json');
        } elseif (input('type') == 6) {
            $data = [
                'room_num' => input('room_num')
            ];
            $this->setReadMessage($data);
            $this->result('', 1, '消息已读', 'json');
        }
    }

    /**
     * @title 查询房间列表
     * @author Leruge
     * @method post
     * @url /api/room_list
     */
    public function roomList()
    {
        $uid = request()->jwt['uid'];
        $serviceIds = model('User')->where(['is_service' => 1])->column('id');
        if (in_array(request()->jwt['uid'], $serviceIds)) {
            // 客服页面 -- 不带私信
            $roomList = model('Chat')->group('room_num')->where('send_id|to_id', '=', $uid)->order('create_time', 'desc')->withAttr([
                'avatar' => function ($value, $info) {
                    if ($info['send_id'] == request()->jwt['uid']) {
                        $avatar = model('User')->where('id', $info['to_id'])->value('avatar');
                    } else {
                        $avatar = model('User')->where('id', $info['send_id'])->value('avatar');
                    }
                    if (substr($avatar, 0, 1) == '/') {
                        return config('extra.app_url') . $avatar;
                    } else {
                        return $avatar;
                    }
                },
                'nickname' => function ($value, $info) {
                    if ($info['send_id'] == request()->jwt['uid']) {
                        $nickname = model('User')->where('id', $info['to_id'])->value('nickname');
                    } else {
                        $nickname = model('User')->where('id', $info['send_id'])->value('nickname');
                    }
                    return $nickname;
                },
                'last_time' => function ($value, $info) {
                    $lastTime = model('Chat')->where('room_num', $info['room_num'])->order('create_time', 'desc')->value('create_time');
                    return date('Y-m-d H:i:s', $lastTime);
                },
                'last_message' => function ($value, $info) {
                    $lastMessageInfo = model('Chat')->where('room_num', $info['room_num'])->order('create_time', 'desc')->find();
                    if ($lastMessageInfo['type'] == 2) {
                        return $lastMessageInfo['content'];
                    } elseif ($lastMessageInfo['type'] == 3) {
                        return '表情';
                    } elseif ($lastMessageInfo['type'] == 4) {
                        return '图片';
                    }
                },
                'no_read_num' => function ($value, $info) {
                    $noReadNum = model('Chat')->where(['room_num' => $info['room_num'], 'to_id' => request()->jwt['uid'], 'is_send_read' => 0])->count();
                    return $noReadNum;
                }
            ])->select()->append(['avatar', 'nickname', 'last_time', 'last_message', 'no_read_num'])->visible(['room_num', 'avatar', 'nickname', 'last_time', 'last_message', 'no_read_num'])->toArray();
        } else {
            // 用户页面 -- 不带私信
            $roomList = [];
            foreach ($serviceIds as $k => $v) {
                $userInfo = model('User')->where('id', $v)->withAttr([
                    'avatar' => function ($value) {
                        if (substr($value, 0, 1) == '/') {
                            return config('extra.app_url') . $value;
                        } else {
                            return $value;
                        }
                    }
                ])->find();
                $roomList[] = [
                    'room_num' => (request()->jwt['uid'] > $v) ? $v . '-' . request()->jwt['uid'] : request()->jwt['uid'] . '-' . $v,
                    'avatar' => $userInfo['avatar'],
                    'nickname' => $userInfo['nickname']
                ];
            }
            foreach ($roomList as $k1 => $v1) {
                $chatInfo = model('Chat')->where('room_num', $v1['room_num'])->order('create_time', 'desc')->withAttr([
                    'last_time' => function ($value, $info) {
                        $lastTime = model('Chat')->where('room_num', $info['room_num'])->order('create_time', 'desc')->value('create_time');
                        return date('Y-m-d H:i:s', $lastTime);
                    },
                    'last_message' => function ($value, $info) {
                        $lastMessageInfo = model('Chat')->where('room_num', $info['room_num'])->order('create_time', 'desc')->find();
                        if ($lastMessageInfo['type'] == 2) {
                            return $lastMessageInfo['content'];
                        } elseif ($lastMessageInfo['type'] == 3) {
                            return '表情';
                        } elseif ($lastMessageInfo['type'] == 4) {
                            return '图片';
                        }
                    },
                    'no_read_num' => function ($value, $info) {
                        $noReadNum = model('Chat')->where(['room_num' => $info['room_num'], 'to_id' => request()->jwt['uid'], 'is_send_read' => 0])->count();
                        return $noReadNum;
                    }
                ])->find();
                if ($chatInfo) {
                    $roomList[$k1]['last_time'] = $chatInfo['last_time'];
                    $roomList[$k1]['last_message'] = $chatInfo['last_message'];
                    $roomList[$k1]['no_read_num'] = $chatInfo['no_read_num'];
                } else {
                    $roomList[$k1]['last_time'] = '无';
                    $roomList[$k1]['last_message'] = '无';
                    $roomList[$k1]['no_read_num'] = 0;
                }
            }
        }

//        $roomList = array_merge($roomList, $userChatList);
        if (count($roomList)) {
            $this->result(['room_list' => $roomList], 1, '房间列表获取成功', 'json');
        } else {
            $this->result(['room_list' => $roomList], 0, '房间列表获取成功', 'json');
        }
    }

    /**
     * @title 客服房间
     * @author Leruge
     * @method post
     * @url /api/service_room
     *
     * @return room_num:房间号
     */
    public function serviceRoom()
    {
        $serviceId = model('User')->where(['is_service' => 1])->value('id');
        $nickname = model('User')->where(['is_service' => 1])->value('nickname');
        if ($serviceId == request()->jwt['uid']) {
            $this->result('', 0, '客服不能跟客服聊天', 'json');
        } else {
            if ($serviceId > request()->jwt['uid']) {
                return $this->result(['room_num' => request()->jwt['uid'] . '-' . $serviceId, 'nickname' => $nickname], 1, '获取房间成功', 'json');
            } else {
                return $this->result(['room_num' => $serviceId . '-' . request()->jwt['uid'], 'nickname' => $nickname], 1, '获取房间成功', 'json');
            }
        }
    }

    /**
     * @title 房间聊天信息
     * @author Leruge
     * @method post
     * @url /api/chat_detail
     *
     * @param name:room_num type:string require:1 desc:房间号
     */
    public function chatDetail()
    {
        $data = [
            'room_num' => input('room_num')
        ];
        $messageList = model('Chat')->where('room_num', $data['room_num'])->order(['create_time' => 'desc', 'id' => 'desc'])->limit(10)->withAttr([
            'type' => function () {
                return 5;
            },
            'avatar' => function ($value, $info) {
                $avatar = model('User')->where('id', $info['send_id'])->value('avatar');
                if (substr($avatar, 0, 1) == '/') {
                    return config('extra.app_url') . $avatar;
                } else {
                    return $avatar;
                }
            },
            'nickname' => function ($value, $info) {
                $nickname = model('User')->where('id', $info['send_id'])->value('nickname');
                return $nickname;
            },
            'content_type' => function ($value, $info) {
                return $info['type'];
            }
        ])->select()->append(['type', 'avatar', 'nickname', 'content_type'])->visible(['type', 'id', 'room_num', 'send_id', 'avatar', 'nickname', 'create_time', 'content', 'content_type'])->reverse();
        if ($messageList->isEmpty()) {
            $this->result('', 0, '没有聊天信息', 'json');
        } else {
            $this->result(['message_list' => $messageList], 1, '获取聊天列表成功', 'json');
        }
    }

    /**
     * @title 下拉加载更多聊天信息
     * @author Leruge
     * @method post
     * @url /api/more_chat_detail
     *
     * @param name:room_num type:string require:1 desc:房间号
     * @param name:message_id type:int require:1 desc:聊天ID
     */
    public function moreChatDetail()
    {
        $data = [
            'id' => input('message_id'),
            'room_num' => input('room_num')
        ];
        $where = [
            ['room_num', '=', $data['room_num']],
            ['id', '<', $data['id']]
        ];
        $messageList = model('Chat')->where($where)->order(['create_time' => 'desc', 'id' => 'desc'])->limit(10)->withAttr([
            'type' => function () {
                return 5;
            },
            'avatar' => function ($value, $info) {
                $avatar = model('User')->where('id', $info['send_id'])->value('avatar');
                if (substr($avatar, 0, 1) == '/') {
                    return config('extra.app_url') . $avatar;
                } else {
                    return $avatar;
                }
            },
            'nickname' => function ($value, $info) {
                $nickname = model('User')->where('id', $info['send_id'])->value('nickname');
                return $nickname;
            },
            'content_type' => function ($value, $info) {
                return $info['type'];
            }
        ])->select()->append(['type', 'avatar', 'nickname', 'content_type'])->visible(['type', 'id', 'room_num', 'send_id', 'avatar', 'nickname', 'create_time', 'content', 'content_type'])->reverse();
        if ($messageList->isEmpty()) {
            $this->result('', 0, '没有更多聊天信息了', 'json');
        } else {
            $this->result(['message_list' => $messageList], 1, '获取更多聊天信息成功', 'json');
        }
    }

    // 绑定用户
    private function bindUser($data)
    {
        Gateway::$registerAddress = '127.0.0.1:1238';
        Gateway::bindUid($data['client_id'], request()->jwt['uid']);
    }

    // 发送消息
    private function sendMessage($message)
    {
        $userInfo = model('User')->where('id', request()->jwt['uid'])->withAttr([
            'avatar' => function ($value) {
                if (substr($value, 0, 1) == '/') {
                    return config('extra.app_url') . $value;
                } else {
                    return $value;
                }
            }
        ])->find();
        $userArray = explode('-', $message['room_num']);
        $sendId = request()->jwt['uid'];
        $key  = array_search($sendId, $userArray);
        array_splice($userArray, $key, 1);
        $toId = $userArray[0];
        $data = [
            'type' => 5,
            'room_num' => $message['room_num'],
            'send_id' => $sendId,
            'avatar' => $userInfo['avatar'],
            'nickname' => $userInfo['nickname'],
            'create_time' => date('Y-m-d H:i:s'),
            'content' => $message['content'],
            'content_type' => $message['type']
        ];
        $isOnline = Gateway::isUidOnline($toId);
        if ($isOnline) {
            model('Chat')->save(['room_num' => $message['room_num'], 'send_id' => $sendId, 'to_id' => $toId, 'type' => $message['type'], 'content' => $message['content'], 'is_to_read' => 0]);
            $data['id'] = model('Chat')->id;
            Gateway::sendToUid($sendId, json_encode($data));
            Gateway::sendToUid($toId, json_encode($data));
        } else {
            model('Chat')->save(['room_num' => $message['room_num'], 'send_id' => $sendId, 'to_id' => $toId, 'type' => $message['type'], 'content' => $message['content'], 'is_to_read' => 0]);
            $data['id'] = model('Chat')->id;
            Gateway::sendToUid($sendId, json_encode($data));
        }
    }

    // 设置消息已读
    private function setReadMessage($data)
    {
        $map = [
            ['room_num', '=', $data['room_num']],
            ['create_time', '<', time()],
            ['to_id', '=', request()->jwt['uid']]
        ];
        model('Chat')->isUpdate(true, $map)->save(['is_to_read' => 1]);
    }
}
